package com.jmga.ecogasfinder.activities.maps;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.jmga.ecogasfinder.GasStation;
import com.jmga.ecogasfinder.R;
import com.jmga.ecogasfinder.activities.maps.overlays.GasStationOverlay;

public class ECOGasStationFinderMapActivity extends MapActivity {

	ArrayAdapter<GasStation> aa;
	ArrayList<GasStation> gasStations = new ArrayList<GasStation>();
	private int gasType = 0;

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	MapController mapController;
	GasStationOverlay positionOverlay;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		MapView myMapView = (MapView) findViewById(R.id.myMapView);
		mapController = myMapView.getController();
		myMapView.setBuiltInZoomControls(true);
		myMapView.setSatellite(false);
		myMapView.displayZoomControls(true);
		mapController.setZoom(13);
		refreshGSList();

		List<Overlay> overlays = myMapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.green_gas_pump_md);
		
	     if (drawable != null) {
             Bitmap bitmapOrg = ((BitmapDrawable) drawable).getBitmap();
             int width = bitmapOrg.getWidth();
             int height = bitmapOrg.getHeight();
             int newWidth = 50;
             int newHeight = 50;
             // calculate the scale
             float scaleWidth = ((float) newWidth) / width;
             float scaleHeight = ((float) newHeight) / height;
             // create a matrix for the manipulation
             Matrix matrix = new Matrix();
             // resize the bit map
             matrix.postScale(scaleWidth, scaleHeight);
             Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
             width, height, matrix, true);
             // make a Drawable from Bitmap to allow to set the BitMap
             drawable = new BitmapDrawable(resizedBitmap);
         }
		positionOverlay = new GasStationOverlay(drawable,this);
		
		for(GasStation gasStation : gasStations) {
			GeoPoint geoPoint = new GeoPoint(Double.valueOf(gasStation.getLocation().getLatitude()* 1E6).intValue(), Double.valueOf(gasStation.getLocation().getLongitude()* 1E6).intValue());
			OverlayItem overlayitem = new OverlayItem(geoPoint, gasStation.getOperador(), String.valueOf(gasStation.getPrecio()));
			positionOverlay.addOverlay(overlayitem);
		}
		
		overlays.add(positionOverlay);

		LocationManager locationManager;
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(context);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String provider = locationManager.getBestProvider(criteria, true);

		Location location = locationManager.getLastKnownLocation(provider);

		updateWithNewLocation(location);

		locationManager.requestLocationUpdates(provider, 2000, 10,
				locationListener);
	}

	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}

		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	private void updateWithNewLocation(Location location) {
		String latLongString;
		TextView myLocationText;
		myLocationText = (TextView) findViewById(R.id.myLocationText);
		String addressString = "No address found";

		if (location != null) {
			// Update my location marker
			positionOverlay.setLocation(location);
			positionOverlay.setGasStations(gasStations);

			// Update the map location.
			Double geoLat = location.getLatitude() * 1E6;
			Double geoLng = location.getLongitude() * 1E6;
			GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());

			mapController.animateTo(point);

			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongString = "Lat:" + lat + "\nLong:" + lng;

			double latitude = location.getLatitude();
			double longitude = location.getLongitude();

			Geocoder gc = new Geocoder(this, Locale.getDefault());
			try {
				List<Address> addresses = gc.getFromLocation(latitude,
						longitude, 1);
				StringBuilder sb = new StringBuilder();
				if (addresses.size() > 0) {
					Address address = addresses.get(0);

					for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
						sb.append(address.getAddressLine(i)).append("\n");

					sb.append(address.getLocality()).append("\n");
					sb.append(address.getPostalCode()).append("\n");
					sb.append(address.getCountryName());
				}
				addressString = sb.toString();
			} catch (IOException e) {
			}
		} else {
			latLongString = "No location found";
		}
		myLocationText.setText("Your Current Position is:\n" + latLongString
				+ "\n" + addressString);
	}
	
	private void refreshGSList() {
		  // Get the XML
		  URL url;
		  try {
		    String quakeFeed = getString(R.string.gas_feed);
		    url = new URL(quakeFeed.concat("&tipoCarburante=" + gasType));
//			url = new URL("http://doc-00-2c-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/p2cfehu6pcbm71bvkj4ekrj401g4la4g/1324211400000/14984451393191252265/*/0B10GxUgpi0Z1ZmM0MjEwZjEtODlkMi00OGE4LWIzNjQtN2EzOWU5Nzc3M2Iy?e=download");
		         
		    URLConnection connection;
		    connection = url.openConnection();
		       
		    HttpURLConnection httpConnection = (HttpURLConnection)connection; 
		    int responseCode = httpConnection.getResponseCode(); 

		    if (responseCode == HttpURLConnection.HTTP_OK) { 
		      InputStream in = httpConnection.getInputStream(); 
		          
		      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		      DocumentBuilder db = dbf.newDocumentBuilder();

		      // Parse the earthquake feed.
		      Document dom = db.parse(in);      
		      Element docEle = dom.getDocumentElement();
		        
		      // Clear the old earthquakes
		      gasStations.clear();
		          
		      // Get a list of each earthquake entry.
		      NodeList nl = docEle.getElementsByTagName("ms:estaciones_servicio_brief");
		      if (nl != null && nl.getLength() > 0) {
		        for (int i = 0 ; i < nl.getLength(); i++) {
		          Element entry = (Element)nl.item(i);
		          Element rotuloElement = (Element)entry.getElementsByTagName("ms:Rotulo").item(0);
		          Element operadorElement = (Element)entry.getElementsByTagName("ms:Operador").item(0);
		          Element direccionElement = (Element)entry.getElementsByTagName("ms:Direccion").item(0);
		          Element margenElement = (Element)entry.getElementsByTagName("ms:Margen").item(0);
		          Element cPostalElement = (Element)entry.getElementsByTagName("ms:CPostal").item(0);
		          Element provinciaElement = (Element)entry.getElementsByTagName("ms:Provincia").item(0);
		          Element localidadElement = (Element)entry.getElementsByTagName("ms:Localidad").item(0);
		          Element precioElement = (Element)entry.getElementsByTagName("ms:Precio").item(0);
		          Element fechaElement = (Element)entry.getElementsByTagName("ms:Fecha").item(0);
		          Element horaElement = (Element)entry.getElementsByTagName("ms:Hora").item(0);
		          Element tipoVentaElement = (Element)entry.getElementsByTagName("ms:TipoVenta").item(0);
		          Element remisionElement = (Element)entry.getElementsByTagName("ms:Remision").item(0);
		          Element coordXElement = (Element)entry.getElementsByTagName("ms:CoordenadaX_dec").item(0);
		          Element coordYElement = (Element)entry.getElementsByTagName("ms:CoordenadaY_dec").item(0);
		          
		          String rotuloString = rotuloElement.getFirstChild().getNodeValue();
		      	  String operadorString = operadorElement.getFirstChild().getNodeValue();
		      	  String direccionString = direccionElement.getFirstChild().getNodeValue();
		      	  String margenString = margenElement.getFirstChild().getNodeValue();
		      	  String codigoPostalString = cPostalElement.getFirstChild().getNodeValue();
		      	  String provinciaString = provinciaElement.getFirstChild().getNodeValue();
		      	  String localidadString = localidadElement.getFirstChild().getNodeValue();
		      	  String precioString = precioElement.getFirstChild().getNodeValue();
		      	  String fechaString = fechaElement.getFirstChild().getNodeValue();
		      	  String horaString = horaElement.getFirstChild().getNodeValue();
		      	  String tipoVentaString = tipoVentaElement.getFirstChild().getNodeValue();
		      	  String remisionString = remisionElement.getFirstChild().getNodeValue();
		      	  String coordXString = coordXElement.getFirstChild().getNodeValue();
		      	  String coordYString = coordYElement.getFirstChild().getNodeValue();

		          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
		          Date fecha = new GregorianCalendar(0,0,0).getTime();
		          double precio = 0d;
		          try {
		        	  fecha = sdf.parse(fechaString + " " +horaString);
			          NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
			          precio = (format.parse(precioString)).doubleValue();
		          } catch (ParseException e) {
		            e.printStackTrace();
		          }
		         	
		          Location l = new Location("dummyGPS");
		          l.setLatitude(Double.parseDouble(coordYString));
		          l.setLongitude(Double.parseDouble(coordXString));
		          		              
		          GasStation gasStation = new GasStation(rotuloString, operadorString, direccionString, margenString, codigoPostalString, provinciaString, localidadString, fecha, tipoVentaString, remisionString, l, precio);

		          addNewGS(gasStation);
		        }
		      }
		    }
		  } catch (MalformedURLException e) {
		    e.printStackTrace();
		  } catch (IOException e) {
		    e.printStackTrace();
		  } catch (ParserConfigurationException e) {
		    e.printStackTrace();
		  } catch (SAXException e) {
		    e.printStackTrace();
		  }
		  finally {
		  }
		}

	    private void addNewGS(GasStation gasStation) {
		  gasStations.add(gasStation);
		}
}
